import BiosafetyAPI from '../../common/api/biosafety/auditmain.api.js';
import doT from '../../../vendor/template/doT.js';
import { DictionaryType, requestDict } from '../../common/dictionary/dictionary-type.js';
import { uploadFile, requestFilePath, publicFileDraw, sliceFileName } from '../../common/api/file-request.js';

(function (window, document, $) {
    let _vm,
        _auditTypeData,
        listindex = '',
        rectifyOptions;
    const detailsTemplate = doT.template($('#details-template').text());
    const _json = Utils.ParsingUrl(window.location);

    $(function () {
        $('body').attr('data-weui-theme', 'light'); //强制光明模式
        initVue();
    });

    const initVue = () => {
        _vm = new Vue({
            el: '#rectify-audit',
            data() {
                return {
                    form: {
                        result: '',
                        remark: '',
                        images: '',
                        attachList: [],
                        auditFormBillId: '',
                        auditFormBillEntrySeq: '',
                    },
                    type: '',
                    isUploading: false,
                };
            },
            mounted() {
                this.initSelect();
                this.initUpload();
                this.initGallery();
            },
            created() {
                let url = location.href;
                let params = {}; // url参数
                for (let key of new URL(url).searchParams.entries()) {
                    key[1] ? (params[key[0]] = key[1]) : '';
                }
                this.form.auditFormBillId = params.auditFormBillId;
                this.form.auditFormBillEntrySeq = params.seq;
                this.type = params.type;
            },
            methods: {
                initSelect() {
                    requestDict(DictionaryType.RESULT_TYPE).then((res) => {
                        rectifyOptions = res.data.map((item) => {
                            return {
                                id: item.value,
                                text: item.displayName,
                            };
                        });
                        $(`#result`).select2({
                            placeholder: '请选择整改情况...', //默认文字提示
                            language: 'zh-CN', //汉化
                            width: '100%',
                            data: rectifyOptions,
                        });
                        $('select#result').val('').trigger('change');
                        $(`select#result`).on('change', () => {
                            this.form.result = $(`select#result`).val();
                        });
                    });
                },
                // 点击取消 返回详情
                backDetail() {
                    location.href = `../biosafety/detailsaudit.html?v=${Utils.GetTime()}&id=${this.form.auditFormBillId}&type=${this.type}&eid=${_json.eid}`;
                },
                // 点击提交
                submit() {
                    let params = this.form;
                    if (!params.result) {
                        $.toptip('请选择整改情况', 'warning');
                    }
                    params.images = params.attachList.map((item) => item.imageId).join(',');
                    BiosafetyAPI.submitRectify(params).then((res) => {
                        $.toptip('提交成功', 'success');
                        setTimeout(() => {
                            this.backDetail();
                        }, 500);
                    });
                },
                // 初始化图片预览组件
                initGallery() {
                    let that = this;
                    $('#uploaderFiles').click(function (e) {
                        let target = e.target;
                        while (!target.classList.contains('weui-uploader__file') && target) {
                            target = target.parentNode;
                        }
                        if (!target) return;
                        //从图片对应的li标签中获得所需属性
                        let gallery = weui.gallery($(target).attr('data-url'), {
                            className: 'custom-name',
                            onDelete: function () {
                                //删除图片的回调
                                $.confirm({
                                    title: '删除提示',
                                    text: '确定删除该图片？',
                                    onOK: function () {
                                        let _id = $(target).attr('data-id');
                                        that.form.attachList = that.form.attachList.filter((item) => item.id != _id);
                                        target.remove();
                                        gallery.hide();
                                    },
                                    onCancel: function () {},
                                });
                            },
                        });
                    });
                },
                // 初始化上传组件
                initUpload() {
                    let that = this;
                    weui.uploader('#uploader', {
                        url: '',
                        auto: false,
                        type: 'file',
                        compress: { isNoTCompress: true },
                        onBeforeQueued: function (files) {
                            // `this` 是轮询到的文件, `files` 是所有文件
                            if (['image/jpg', 'image/jpeg', 'image/png'].indexOf(this.type) < 0) {
                                $.toptip('请上传图片', 'warning');
                                return false; // 阻止文件添加
                            }
                            if (this.size > 8 * 1024 * 1024) {
                                $.toptip('请上传不超过8M的文件', 'warning');
                                return false;
                            }
                            $.showLoading('上传中..');
                            that.isUploading = true;
                        },
                        onQueued: function () {
                            //
                            let formFile = new FormData();
                            let upFiles = this;
                            let file = publicFileDraw(this.name, _vm);
                            let fileName = sliceFileName(upFiles);
                            let newfile = publicFileDraw(fileName, _vm);
                            if (newfile != false && newfile != undefined) {
                                formFile.append('apiobjfile', new window.File([upFiles], newfile, { type: upFiles.type }));
                                that._uploadFileDraw(formFile, upFiles, _vm, newfile);
                            }

                            // if (file != false && file != undefined) {
                            //     formFile.append('apiobjfile', new window.File([this], file, { type: this.type }));
                            //     that._uploadFileDraw(formFile, upFiles, _vm, file);
                            // }
                            // //确认提交
                            // $('.weui-dialog__btn').on('click', function () {
                            //     if ($(this)[0].innerHTML == '确认') {
                            //         let fileName = sliceFileName(upFiles);
                            //         let newfile = publicFileDraw(fileName, _vm);
                            //         if (newfile != false && newfile != undefined) {
                            //             formFile.append('apiobjfile', new window.File([upFiles], newfile, { type: upFiles.type }));
                            //             that._uploadFileDraw(formFile, upFiles, _vm, newfile);
                            //         }
                            //     }
                            // });
                            return true;
                        },
                    });
                },
                // 附件上传
                _uploadFileDraw(formFile, upFiles, _vm, newName) {
                    uploadFile(formFile)
                        .then((res) => {
                            this.isUploading = false;
                            if (res.isSucceed) {
                                let item = {
                                    id: $('#uploaderFiles li').length,
                                    imageId: res.data,
                                    url: upFiles.url,
                                    name: newName,
                                    type: upFiles.name.split('.').pop().toLowerCase(),
                                };
                                this.form.attachList.push(item);
                                let attachList = this.form.attachList;
                                // 在dom上添加图片
                                $('#uploaderFiles li').each(function (i) {
                                    $(this).attr('data-id', attachList[i].id);
                                    $(this).attr('data-image-id', attachList[i].imageId);
                                    $(this).attr('data-name', attachList[i].name);
                                    $(this).attr('data-suffix', attachList[i].type);
                                    if (['jpg', 'jpeg', 'png', 'gif'].indexOf(attachList[i].type) < 0) {
                                        $(this).attr('data-url', '../../../../public/static/images/other/pic_default_uploader.png');
                                        $(this).css({ 'background-image': `url(${'../../../../public/static/images/other/pic_default_uploader.png'})` });
                                    } else {
                                        $(this).attr('data-url', attachList[i].url);
                                        $(this).css({ 'background-image': `url(${attachList[i].url})` });
                                    }
                                });
                                $('.weui-uploader__file-content').hide();
                                $('.weui-uploader__file').removeClass('weui-uploader__file_status');
                            }
                        })
                        .catch((res) => {
                            this.isUploading = false;
                            $('#uploaderFiles li')
                                .eq($('#uploaderFiles li').length - 1)
                                .remove();
                            $.toptip(res.msg, 'error');
                        })
                        .finally((_) => {
                            $.hideLoading();
                            $.closeModal();
                        });
                },
            },
        });
    };
})(window, document, jQuery);
